<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,">










<meta name="description" content="如果你像我一样乐于见到整洁的代码，那么你会尽可能地减少代码中的条件语句。通常情况下，面向对象编程让我们得以避免条件式，并代之以继承和多态。我认为我们应当尽可能地遵循这些原则。 正如我在另一篇文章 JavaScript 整洁代码的最佳实践里提到的，你写的代码不单单是给机器看的，还是给“未来的自己”以及“其他人”看的。 从另一方面来说，由于各式各样的原因，可能我们的代码最终还是会有条件式。也许是修复">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="编写更好的JavaScript条件式和匹配条件的技巧">
<meta property="og:url" content="https://blog.emx6.com/2019/06/29/编写更好的JavaScript条件式和匹配条件的技巧/index.html">
<meta property="og:site_name" content="上帝不会掷骰子">
<meta property="og:description" content="如果你像我一样乐于见到整洁的代码，那么你会尽可能地减少代码中的条件语句。通常情况下，面向对象编程让我们得以避免条件式，并代之以继承和多态。我认为我们应当尽可能地遵循这些原则。 正如我在另一篇文章 JavaScript 整洁代码的最佳实践里提到的，你写的代码不单单是给机器看的，还是给“未来的自己”以及“其他人”看的。 从另一方面来说，由于各式各样的原因，可能我们的代码最终还是会有条件式。也许是修复">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-07T14:59:24.541Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="编写更好的JavaScript条件式和匹配条件的技巧">
<meta name="twitter:description" content="如果你像我一样乐于见到整洁的代码，那么你会尽可能地减少代码中的条件语句。通常情况下，面向对象编程让我们得以避免条件式，并代之以继承和多态。我认为我们应当尽可能地遵循这些原则。 正如我在另一篇文章 JavaScript 整洁代码的最佳实践里提到的，你写的代码不单单是给机器看的，还是给“未来的自己”以及“其他人”看的。 从另一方面来说，由于各式各样的原因，可能我们的代码最终还是会有条件式。也许是修复">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.emx6.com/2019/06/29/编写更好的JavaScript条件式和匹配条件的技巧/">





  <title>编写更好的JavaScript条件式和匹配条件的技巧 | 上帝不会掷骰子</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">上帝不会掷骰子</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.emx6.com/2019/06/29/编写更好的JavaScript条件式和匹配条件的技巧/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Glyn Yu">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="上帝不会掷骰子">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">编写更好的JavaScript条件式和匹配条件的技巧</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-06-29T18:06:54+08:00">
                2019-06-29
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Web/" itemprop="url" rel="index">
                    <span itemprop="name">Web</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2019/06/29/编写更好的JavaScript条件式和匹配条件的技巧/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2019/06/29/编写更好的JavaScript条件式和匹配条件的技巧/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </span></div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>如果你像我一样乐于见到整洁的代码，那么你会尽可能地减少代码中的条件语句。通常情况下，面向对象编程让我们得以避免条件式，并代之以继承和多态。我认为我们应当尽可能地遵循这些原则。</p>
<p>正如我在另一篇文章 JavaScript 整洁代码的最佳实践里提到的，你写的代码不单单是给机器看的，还是给“未来的自己”以及“其他人”看的。</p>
<p>从另一方面来说，由于各式各样的原因，可能我们的代码最终还是会有条件式。也许是修复 bug 的时间很紧，也许是不使用条件语句会对我们的代码库造成大的改动，等等。本文将会解决这些问题，同时帮助你组织所用的条件语句。</p>
<h3 id="技巧"><a href="#技巧" class="headerlink" title="技巧"></a><strong>技巧</strong></h3><p>以下是关于如何构造 if…else 语句以及如何用更少的代码实现更多功能的技巧。阅读愉快！</p>
<h4 id="1-要事第一。小细节，但很重要"><a href="#1-要事第一。小细节，但很重要" class="headerlink" title="1. 要事第一。小细节，但很重要"></a>1. 要事第一。小细节，但很重要</h4><p>不要使用否定条件式（这可能会让人感到疑惑）。同时，使用条件式简写来表示 boolean 值。这个无须再强调了，尤其是否定条件式，这不符合正常的思维方式。<br>不好的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isEmailNotVerified = <span class="function">(<span class="params">email</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 实现</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (!isEmailNotVerified(email)) &#123;</span><br><span class="line">    <span class="comment">// 做一些事...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (isVerified === <span class="literal">true</span>) &#123;</span><br><span class="line">    <span class="comment">// 做一些事...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>好的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isEmailVerified = <span class="function">(<span class="params">email</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 实现</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (isEmailVerified(email)) &#123;</span><br><span class="line">    <span class="comment">// 做一些事...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (isVerified) &#123;</span><br><span class="line">    <span class="comment">// 做一些事...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在，理清了上面的事情后，我们就可以开始了。</p>
<h4 id="2-对于多个条件，使用-Array-includes"><a href="#2-对于多个条件，使用-Array-includes" class="headerlink" title="2. 对于多个条件，使用 Array.includes"></a>2. 对于多个条件，使用 Array.includes</h4><p>假设我们想要在函数中检查汽车模型是 renault 还是 peugeot。那么代码可能是这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkCarModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(model === <span class="string">'renault'</span> || model === <span class="string">'peugeot'</span>) &#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'model valid'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">checkCarModel(<span class="string">'renault'</span>); <span class="comment">// 输出 'model valid'</span></span><br></pre></td></tr></table></figure>

<p>考虑到我们只有两个模型，这么做似乎也还能接受，但如果我们还想要检查另一个或者是几个模型呢？如果我们增加更多 or 语句，那么代码将变得难以维护，且不够整洁。为了让它更加简洁，我们可以像这样重写函数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkCarModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>([<span class="string">'peugeot'</span>, <span class="string">'renault'</span>].includes(model)) &#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'model valid'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">checkCarModel(<span class="string">'renault'</span>); <span class="comment">// 输出 'model valid'</span></span><br></pre></td></tr></table></figure>

<p>上面的代码看起来已经很漂亮了。为了更进一步改善它，我们可以创建一个变量来存放汽车模型：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkCarModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> models = [<span class="string">'peugeot'</span>, <span class="string">'renault'</span>];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(models.includes(model)) &#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'model valid'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">checkCarModel(<span class="string">'renault'</span>); <span class="comment">// 输出 'model valid'</span></span><br></pre></td></tr></table></figure>

<p>现在，如果我们想要检查更多模型，只需要添加一个新的数组元素即可。此外，如果它很重要的话，我们还可以将 models 变量定义在函数作用域外，并在需要的地方重用。这种方式可以让我们集中管理，并使维护变得轻而易举，因为我们只需在代码中更改一个位置。</p>
<h4 id="3-匹配所有条件，使用-Array-every-或者-Array-find"><a href="#3-匹配所有条件，使用-Array-every-或者-Array-find" class="headerlink" title="3. 匹配所有条件，使用 Array.every 或者 Array.find"></a>3. 匹配所有条件，使用 Array.every 或者 Array.find</h4><p>在本例中，我们想要检查每个汽车模型是否都是传入函数的那一个。为了以更加命令式的方式实现，我们会这么做：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cars = [</span><br><span class="line">  &#123; <span class="attr">model</span>: <span class="string">'renault'</span>, <span class="attr">year</span>: <span class="number">1956</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">model</span>: <span class="string">'peugeot'</span>, <span class="attr">year</span>: <span class="number">1968</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">model</span>: <span class="string">'ford'</span>, <span class="attr">year</span>: <span class="number">1977</span> &#125;</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> checkEveryModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> isValid = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> car <span class="keyword">of</span> cars) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!isValid) &#123;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    isValid = car.model === model;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> isValid;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(checkEveryModel(<span class="string">'renault'</span>)); <span class="comment">// 输出 false</span></span><br></pre></td></tr></table></figure>

<p>如果你更喜欢以命令式的风格行事，上面的代码或许还不错。另一方面，如果你不关心其背后发生了什么，那么你可以重写上面的函数并使用 Array.every 或者 Array.find 来达到相同的结果。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkEveryModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> cars.every(<span class="function"><span class="params">car</span> =&gt;</span> car.model === model);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(checkEveryModel(<span class="string">'renault'</span>)); <span class="comment">// 输出 false</span></span><br></pre></td></tr></table></figure>

<p>通过使用 Array.find 并做轻微的调整，我们可以达到相同的结果。两者的表现是一致的，因为两个函数都为数组中的每一个元素执行了回调，并且在找到一个 falsy 项时立即返回 false。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkEveryModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> cars.find(<span class="function"><span class="params">car</span> =&gt;</span> car.model !== model) === <span class="literal">undefined</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(checkEveryModel(<span class="string">'renault'</span>)); <span class="comment">// 输出 false</span></span><br></pre></td></tr></table></figure>

<h4 id="4-匹配部分条件，使用-Array-some"><a href="#4-匹配部分条件，使用-Array-some" class="headerlink" title="4. 匹配部分条件，使用 Array.some"></a>4. 匹配部分条件，使用 Array.some</h4><p>Array.every 匹配所有条件，这个方法则可以轻松地检查我们的数组是否包含某一个或某几个元素。为此，我们需要提供一个回调并基于条件返回一个布尔值。</p>
<p>我们可以通过编写一个类似的 for…loop 语句来实现相同的结果，就像之前写的一样。但幸运的是，有很酷的 JavaScript 函数可以来帮助我们完成这件事。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cars = [</span><br><span class="line">  &#123; <span class="attr">model</span>: <span class="string">'renault'</span>, <span class="attr">year</span>: <span class="number">1956</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">model</span>: <span class="string">'peugeot'</span>, <span class="attr">year</span>: <span class="number">1968</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">model</span>: <span class="string">'ford'</span>, <span class="attr">year</span>: <span class="number">1977</span> &#125;</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> checkForAnyModel = <span class="function">(<span class="params">model</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> cars.some(<span class="function"><span class="params">car</span> =&gt;</span> car.model === model);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(checkForAnyModel(<span class="string">'renault'</span>)); <span class="comment">// 输出 true</span></span><br></pre></td></tr></table></figure>

<h4 id="5-提前返回而不是使用-if…else-分支"><a href="#5-提前返回而不是使用-if…else-分支" class="headerlink" title="5. 提前返回而不是使用 if…else 分支"></a>5. 提前返回而不是使用 if…else 分支</h4><p>当我还是学生的时候，就有人教过我：一个函数应该只有一个返回语句，并且只从一个地方返回。如果细心处理，这个方法倒也还好。我这么说也就意味着，我们应该意识到它在某些情况下可能会引起条件式嵌套地狱。如果不受控制，多个分支和 if…else 嵌套将会让我们感到很痛苦。</p>
<p>另一方面，如果代码库很大且包含很多行代码，位于深层的一个返回语句可能会带来问题。现在我们都实行关注点分离和 SOLID 原则，因此，代码行过多这种情况挺罕见的。</p>
<p>举例来解释这个问题。假设我们想要显示所给车辆的模型和生产年份：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkModel = <span class="function">(<span class="params">car</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> result; <span class="comment">// 首先，定义一个 result 变量</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 检查是否有车</span></span><br><span class="line">  <span class="keyword">if</span>(car) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 检查是否有车的模型</span></span><br><span class="line">    <span class="keyword">if</span> (car.model) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 检查是否有车的年份</span></span><br><span class="line">      <span class="keyword">if</span>(car.year) &#123;</span><br><span class="line">        result = <span class="string">`Car model: <span class="subst">$&#123;car.model&#125;</span>; Manufacturing year: <span class="subst">$&#123;car.year&#125;</span>;`</span>;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        result = <span class="string">'No car year'</span>;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      result = <span class="string">'No car model'</span></span><br><span class="line">    &#125;   </span><br><span class="line"></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    result = <span class="string">'No car'</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> result; <span class="comment">// 我们的单独的返回语句</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(checkModel()); <span class="comment">// 输出 'No car'</span></span><br><span class="line"><span class="built_in">console</span>.log(checkModel(&#123; <span class="attr">year</span>: <span class="number">1988</span> &#125;)); <span class="comment">// 输出 'No car model'</span></span><br><span class="line"><span class="built_in">console</span>.log(checkModel(&#123; <span class="attr">model</span>: <span class="string">'ford'</span> &#125;)); <span class="comment">// 输出 'No car year'</span></span><br><span class="line"><span class="built_in">console</span>.log(checkModel(&#123; <span class="attr">model</span>: <span class="string">'ford'</span>, <span class="attr">year</span>: <span class="number">1988</span> &#125;)); <span class="comment">// 输出 'Car model: ford; Manufacturing year: 1988;'</span></span><br></pre></td></tr></table></figure>

<p>正如你所看到的，即使本例的问题很简单，上面的代码也实在太长了。可以想象一下，如果我们有更加复杂的逻辑会发生什么事。大量的 if…else 语句。</p>
<p>我们可以重构上面的函数，分解成多个步骤并稍做改善。例如，使用三元操作符，包括 &amp;&amp; 条件式等。不过，这里我直接跳到最后，向你展示借助现代 JavaScript 特性和多个返回语句，代码可以有多简洁。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> checkModel = <span class="function">(<span class="params">&#123;model, year&#125; = &#123;&#125;</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span>(!model &amp;&amp; !year) <span class="keyword">return</span> <span class="string">'No car'</span>;</span><br><span class="line">  <span class="keyword">if</span>(!model) <span class="keyword">return</span> <span class="string">'No car model'</span>;</span><br><span class="line">  <span class="keyword">if</span>(!year) <span class="keyword">return</span> <span class="string">'No car year'</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 这里可以任意操作模型或年份</span></span><br><span class="line">  <span class="comment">// 确保它们存在</span></span><br><span class="line">  <span class="comment">// 无需更多检查</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// doSomething(model);</span></span><br><span class="line">  <span class="comment">// doSomethingElse(year);</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="string">`Car model: <span class="subst">$&#123;model&#125;</span>; Manufacturing year: <span class="subst">$&#123;year&#125;</span>;`</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(checkModel()); <span class="comment">// 输出 'No car'</span></span><br><span class="line"><span class="built_in">console</span>.log(checkModel(&#123; <span class="attr">year</span>: <span class="number">1988</span> &#125;)); <span class="comment">// 输出 'No car model'</span></span><br><span class="line"><span class="built_in">console</span>.log(checkModel(&#123; <span class="attr">model</span>: <span class="string">'ford'</span> &#125;)); <span class="comment">// 输出 'No car year'</span></span><br><span class="line"><span class="built_in">console</span>.log(checkModel(&#123; <span class="attr">model</span>: <span class="string">'ford'</span>, <span class="attr">year</span>: <span class="number">1988</span> &#125;)); <span class="comment">// 输出 'Car model: ford; Manufacturing year: 1988;'</span></span><br></pre></td></tr></table></figure>

<p>在重构版本中，我们包含了解构和默认参数。默认参数确保我们在传入 undefined 时有可用于解构的值。注意，如果传入 null ，函数将会抛出错误。这也是之前那个方法的优点所在，因为那个方法在传入 null 的时候会输出 ‘No car’。</p>
<p>对象解构确保函数只取所需。例如，如果我们在给定车辆对象中包含额外属性，则该属性在我们的函数中是无法获取的。</p>
<p>根据偏好，开发者会选择其中一种方式。实践中，编写的代码通常介于两者之间。很多人觉得 if…else 语句更容易理解，并且有助于他们更为轻松地遵循程序流程。</p>
<h4 id="6-使用索引或者映射，而不是-switch-语句"><a href="#6-使用索引或者映射，而不是-switch-语句" class="headerlink" title="6. 使用索引或者映射，而不是 switch 语句"></a>6. 使用索引或者映射，而不是 switch 语句</h4><p>假设我们想要基于给定的国家获取汽车模型。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> getCarsByState = <span class="function">(<span class="params">state</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">switch</span> (state) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'usa'</span>:</span><br><span class="line">      <span class="keyword">return</span> [<span class="string">'Ford'</span>, <span class="string">'Dodge'</span>];</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'france'</span>:</span><br><span class="line">      <span class="keyword">return</span> [<span class="string">'Renault'</span>, <span class="string">'Peugeot'</span>];</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'italy'</span>:</span><br><span class="line">      <span class="keyword">return</span> [<span class="string">'Fiat'</span>];</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">      <span class="keyword">return</span> [];</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState()); <span class="comment">// 输出 []</span></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState(<span class="string">'usa'</span>)); <span class="comment">// 输出 ['Ford', 'Dodge']</span></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState(<span class="string">'italy'</span>)); <span class="comment">// 输出 ['Fiat']</span></span><br></pre></td></tr></table></figure>

<p>上诉代码可以重构，完全去除 switch 语句。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> cars = <span class="keyword">new</span> <span class="built_in">Map</span>()</span><br><span class="line">  .set(<span class="string">'usa'</span>, [<span class="string">'Ford'</span>, <span class="string">'Dodge'</span>])</span><br><span class="line">  .set(<span class="string">'france'</span>, [<span class="string">'Renault'</span>, <span class="string">'Peugeot'</span>])</span><br><span class="line">  .set(<span class="string">'italy'</span>, [<span class="string">'Fiat'</span>]);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getCarsByState = <span class="function">(<span class="params">state</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> cars.get(state) || [];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState()); <span class="comment">// 输出 []</span></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState(<span class="string">'usa'</span>)); <span class="comment">//输出 ['Ford', 'Dodge']</span></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState(<span class="string">'italy'</span>)); <span class="comment">// 输出 ['Fiat']</span></span><br></pre></td></tr></table></figure>

<p>或者，我们还可以为包含可用汽车列表的每个国家创建一个类，并在需要的时候使用。不过这个就是题外话了，本文的主题是关于条件句的。更恰当的修改是使用对象字面量。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> carState = &#123;</span><br><span class="line">  usa: [<span class="string">'Ford'</span>, <span class="string">'Dodge'</span>],</span><br><span class="line">  france: [<span class="string">'Renault'</span>, <span class="string">'Peugeot'</span>],</span><br><span class="line">  italy: [<span class="string">'Fiat'</span>]</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getCarsByState = <span class="function">(<span class="params">state</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> carState[state] || [];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState()); <span class="comment">// 输出 []</span></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState(<span class="string">'usa'</span>)); <span class="comment">// 输出 ['Ford', 'Dodge']</span></span><br><span class="line"><span class="built_in">console</span>.log(getCarsByState(<span class="string">'france'</span>)); <span class="comment">// 输出 ['Renault', 'Peugeot']</span></span><br></pre></td></tr></table></figure>

<h4 id="7-使用自判断链接和空合并"><a href="#7-使用自判断链接和空合并" class="headerlink" title="7. 使用自判断链接和空合并"></a>7. 使用自判断链接和空合并</h4><p>到了这一小节，我终于可以说“最后”了。在我看来，这两个功能对于 JavaScript 语言来说是非常有用的。作为一个来自 C# 世界的人，可以说我经常使用它们。</p>
<p>在写这篇文章的时候，这些还没有得到完全的支持。因此，对于以这种方式编写的代码，你需要使用 Babel 进行编译。你可以在自判断链接这里以及在空合并这里查阅。</p>
<p>自判断链接允许我们在没有显式检查中间节点是否存在的时候处理树形结构，空合并可以确保节点不存在时会有一个默认值，配合自判断链接使用会有不错的效果。</p>
<p>让我们用一些例子来支撑上面的结论。一开始，我们还是用以前的老方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> car = &#123;</span><br><span class="line">  model: <span class="string">'Fiesta'</span>,</span><br><span class="line">  manufacturer: &#123;</span><br><span class="line">    name: <span class="string">'Ford'</span>,</span><br><span class="line">    address: &#123;</span><br><span class="line">      street: <span class="string">'Some Street Name'</span>,</span><br><span class="line">      number: <span class="string">'5555'</span>,</span><br><span class="line">      state: <span class="string">'USA'</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取汽车模型</span></span><br><span class="line"><span class="keyword">const</span> model = car &amp;&amp; car.model || <span class="string">'default model'</span>;</span><br><span class="line"><span class="comment">// 获取厂商地址</span></span><br><span class="line"><span class="keyword">const</span> street = car &amp;&amp; car.manufacturer &amp;&amp; car.manufacturer.address &amp;&amp; car.manufacturer.address.street || <span class="string">'default street'</span>;</span><br><span class="line"><span class="comment">// 请求一个不存在的属性</span></span><br><span class="line"><span class="keyword">const</span> phoneNumber = car &amp;&amp; car.manufacturer &amp;&amp; car.manufacturer.address &amp;&amp; car.manufacturer.phoneNumber;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(model) <span class="comment">// 输出 'Fiesta'</span></span><br><span class="line"><span class="built_in">console</span>.log(street) <span class="comment">// 输出 'Some Street Name'</span></span><br><span class="line"><span class="built_in">console</span>.log(phoneNumber) <span class="comment">// 输出 undefined</span></span><br><span class="line">因此，如果我们想要知道厂商是否来自 USA 并将结果打印，那么代码是这样的：</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> checkCarManufacturerState = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span>(car &amp;&amp; car.manufacturer &amp;&amp; car.manufacturer.address &amp;&amp; car.manufacturer.address.state === <span class="string">'USA'</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Is from USA'</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">checkCarManufacturerState() <span class="comment">// 输出 'Is from USA'</span></span><br></pre></td></tr></table></figure>

<p>我无需再赘述如果对象结构更加复杂的话，代码会多么混乱了。许多库，例如 lodash，有自己的函数作为替代方案。不过这不是我们想要的，我们想要的是在原生 js 中也能做同样的事。我们来看一下新的方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取汽车模型</span></span><br><span class="line"><span class="keyword">const</span> model = car?.model ?? <span class="string">'default model'</span>;</span><br><span class="line"><span class="comment">// 获取厂商地址</span></span><br><span class="line"><span class="keyword">const</span> street = car?.manufacturer?.address?.street ?? <span class="string">'default street'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 检查汽车厂商是否来自 USA</span></span><br><span class="line"><span class="keyword">const</span> checkCarManufacturerState = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span>(car?.manufacturer?.address?.state === <span class="string">'USA'</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Is from USA'</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这看起来更加漂亮和简洁，对我来说，非常符合逻辑。如果你想知道为什么应该使用 ?? 而不是 || ，只需想一想什么值可以当做 true 或者 false，你将可能有意想不到的输出。</p>
<p>顺便说句题外话。自判断链接同样支持 DOM API，这非常酷，意味着你可以这么做：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> value = <span class="built_in">document</span>.querySelector(<span class="string">'input#user-name'</span>)?.value;</span><br></pre></td></tr></table></figure>

<blockquote><p>关于本文<br>译者：@chorer<br>译文：<a href="https://chorer.github.io/2019/06/24/Trs-更好的JavaScript条件式和匹配标准技巧/" target="_blank" rel="noopener">https://chorer.github.io/2019/06/24/Trs-更好的JavaScript条件式和匹配标准技巧/</a><br>作者：@Milos Protic<br>原文：<a href="https://devinduct.com/blogpost/35/tips-and-tricks-for-better-javascript-conditionals-and-match-criteria" target="_blank" rel="noopener">https://devinduct.com/blogpost/35/tips-and-tricks-for-better-javascript-conditionals-and-match-criteria</a></p>
</blockquote>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/06/27/拆解JavaScript中的异步模式/" rel="next" title="拆解JavaScript中的异步模式">
                <i class="fa fa-chevron-left"></i> 拆解JavaScript中的异步模式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/01/从浏览器地址栏输入url到显示页面的步骤/" rel="prev" title="从浏览器地址栏输入url到显示页面的步骤">
                从浏览器地址栏输入url到显示页面的步骤 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Glyn Yu</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">48</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zjycp" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:chnzjycp@foxmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#技巧"><span class="nav-number">1.</span> <span class="nav-text">技巧</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-要事第一。小细节，但很重要"><span class="nav-number">1.1.</span> <span class="nav-text">1. 要事第一。小细节，但很重要</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-对于多个条件，使用-Array-includes"><span class="nav-number">1.2.</span> <span class="nav-text">2. 对于多个条件，使用 Array.includes</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-匹配所有条件，使用-Array-every-或者-Array-find"><span class="nav-number">1.3.</span> <span class="nav-text">3. 匹配所有条件，使用 Array.every 或者 Array.find</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-匹配部分条件，使用-Array-some"><span class="nav-number">1.4.</span> <span class="nav-text">4. 匹配部分条件，使用 Array.some</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-提前返回而不是使用-if…else-分支"><span class="nav-number">1.5.</span> <span class="nav-text">5. 提前返回而不是使用 if…else 分支</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-使用索引或者映射，而不是-switch-语句"><span class="nav-number">1.6.</span> <span class="nav-text">6. 使用索引或者映射，而不是 switch 语句</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-使用自判断链接和空合并"><span class="nav-number">1.7.</span> <span class="nav-text">7. 使用自判断链接和空合并</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Glyn Yu</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277767124&web_id=1277767124" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cyuiUNe9o';
      var conf = '7ce07412b2706ea50ada6a787faf513f';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  





  

  

  

  
  

  

  

  

</body>
</html>
